package com.psm.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.psm.interceptor.IndexInterceptor;
import com.psm.model.DataGrid;
import com.psm.model.WxSetting;
import com.psm.weixin.AccessToken;
import com.psm.weixin.AccessTokenApi;
import com.psm.weixin.ApiConfig;
import com.psm.weixin.ApiConfigKit;

/**
 * 
 * @author 广州朴石茗文化发展有限公司 @Email pushiming@sina.cn
 * Jul 22, 2015 
 * TODO
 */
@Before(IndexInterceptor.class)
public class WXSettingController extends BaseController<WxSetting>{
	
	public Logger log=Logger.getLogger(getClass());
	/**
	 * 主页
	 */
    public void index(){
//    	CardInfo info = new ReadCard().rd();
//    	System.out.println(info.getIdaddress());
        render("index.html");
    }
    
    
    /**
     * 列表数据
     */
    public void listJson(){

        List<Object> param = new ArrayList<Object>();
 
        Page<Record> p = Db.paginate(this.getParaToInt("page", 1), this.getParaToInt("rows", 20), "select t.* ", "from " + WxSetting.tableName + " t  where 1=1 ", param.toArray());
        DataGrid dg = new DataGrid();
        dg.setRows(p.getList());
        dg.setTotal(p.getTotalRow());

        renderJson(dg);

    }
    /**
     * 编辑、添加页
     */
    public void edit() {
        try {
        	log.debug("wxsetting-edit=================================");
            Long id = getParaToLong("id");
            
            WxSetting wx = WxSetting.wx.findById(id);
            this.setAttr("po",wx);
        } catch (Exception e) {
            log.error("编辑异常", e);
        }
    }
    /**
     * 保存信息
     */
    public void save(){
    	/**
    	 * 获取数据
    	 */
    	 String id = getPara("id","");
         String name = getPara("name","");
         String appid = getPara("appid","");
         String secret = getPara("secret","");
         String grant_type = getPara("grant_type","");
         /**
          * 新建对象
          */
         WxSetting wx = null;
         if("".equals(id)){
             wx = new WxSetting();
         }else{
             wx = WxSetting.wx.findById(id);
         }
         wx.set("wx_name",name);
         wx.set("appid",appid);
         wx.set("secret",secret);
         /**
          * 更新数据
          */
         if("".equals(id)){
        	 //获取AccessToken
        	 ApiConfig ac = new ApiConfig();
     		 ac.setAppId(appid);
     		 ac.setAppSecret(secret);
     		 ApiConfigKit.setThreadLocalApiConfig(ac);
     		 
     		 AccessToken at = AccessTokenApi.getAccessToken();
     		 
    		
        	 wx.set("grant_type", "client_credential");
        	 wx.set("access_token", at.getAccessToken());
        	 wx.set("token_time", System.currentTimeMillis()/1000);
             wx.save();
         }else{
             wx.update();
         }
         this.rendJson_(1, "操作成功");
    }

}
